import React, {Component} from 'react';
import styles from '../Message/index.less';
import qs from 'querystring';
import CSSModules from 'react-css-modules';
import {List} from 'antd';
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';
import {messageNotice as message} from 'common/utils';
import {REPORT_LIST_URL,ARTICLE_URL} from 'constant/url';
import ArticleItem from './Item';

import {Button, Icon} from 'antd';

const pageSize = 5;

class ReportList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      list: [],
      total: 0,
      page: 1,
      radioValue: 1,
      size: pageSize,
    };
  }
  componentDidMount() {
    this.getArticleList(this.getQuery());
  }
  getArticleList = query => {
    this.setState({
      loading: true,
    });
    get(REPORT_LIST_URL, query).then(res => {
      this.setState({
        list: [].concat(this.state.list, res.list),
        total: res.total,
        loading: false,
      });
    });
  };
  getQuery() {
    let carId = qs.parse(this.props.query.replace('?', ''))
      ? qs.parse(this.props.query.replace('?', '')).carId
      : null;
    let query = {
      page: this.state.page,
      size: this.state.size,
    };
    return query;
  }
  fetchMore() {
    this.setState(
      {
        page: this.state.page + 1,
      },
      () => {
        this.getArticleList(this.getQuery());
      },
    );
  }
  handleDelete(id) {
    deleteAxios(`${ARTICLE_URL}/${id}`, {}).then(res => {
      message.success('删除成功！');
      this.setState({page: 1, list: []}, () => {
        this.getArticleList(this.getQuery());
      });
    });
  }
  handleDeleteReport(id) {
    deleteAxios(`${REPORT_LIST_URL}/${id}`, {}).then(res => {
      message.success('删除成功！');
      this.setState({page: 1, list: []}, () => {
        this.getArticleList(this.getQuery());
      });
    });
  }
  render() {
    const {total, list, loading} = this.state,
      loadMore =
        list.length < total ? (
          <div style={{textAlign: 'center', marginTop: 16}}>
            <Button
              onClick={this.fetchMore.bind(this)}
              style={{paddingLeft: 48, paddingRight: 48}}>
              {loading ? (
                <span>
                  <Icon type="loading" /> 加载中...
                </span>
              ) : (
                '加载更多'
              )}
            </Button>
          </div>
        ) : null;
    return (
      <List
        size="large"
        rowKey="id"
        itemLayout="vertical"
        loadMore={loadMore}
        dataSource={list}
        renderItem={item => (
          <ArticleItem
            {...item}
            onDelete={id => {
              this.handleDelete(id);
            }}
            onDeleteReport={id => {
              this.handleDeleteReport(id);
            }}
          />
        )}
      />
    );
  }
}

export default CSSModules(ReportList, styles);
